/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pv168.uloha3.swing.workers;

import cz.muni.fi.pv168.uloha3.common.DBUtils;
import cz.muni.fi.pv168.uloha3.entities.RealEstate;
import cz.muni.fi.pv168.uloha3.entities.RealEstateType;
import cz.muni.fi.pv168.uloha3.exceptions.RealEstateManagerException;
import cz.muni.fi.pv168.uloha3.managers.RealEstateManager;
import cz.muni.fi.pv168.uloha3.managers.impl.RealEstateManagerImpl;
import cz.muni.fi.pv168.uloha3.swing.EstatesTableModel;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author stefan
 */
public class EstateEditSwingWorker extends SwingWorker<Boolean, Object> {
    
    private final String id;
    private final String catastralId;
    private final String address;
    private final String type;
    private final EstatesTableModel model;

    public EstateEditSwingWorker(String id, String catastralId, String address, String type, EstatesTableModel model) {
        this.id = id;
        this.catastralId = catastralId;
        this.address = address;
        this.type = type;
        this.model = model;
    }

    @Override
    protected Boolean doInBackground() throws Exception {
        DataSource dataSource = DBUtils.initConnector();
        
        RealEstateManager managerEstate = new RealEstateManagerImpl();
        managerEstate.setDataSource(dataSource);
        
        RealEstate estate = new RealEstate();
        estate.setId(new Long(id));
        estate.setCatastralId(catastralId);
        estate.setAddress(address);
        estate.setType(RealEstateType.fromValue(type));
        
        try {
            managerEstate.editRealEstate(estate);
        } catch (RealEstateManagerException ex) {
            
            Logger.getLogger(EstateEditSwingWorker.class.getName()).log(Level.WARNING, ex.getMessage());
            JOptionPane.showMessageDialog(null, "Estate could not be updated (" + ex.getMessage() + ")");
            return false;
        }

        model.updateEstate(estate);
        JOptionPane.showMessageDialog(null, "Estate updated");
        return true;
    }
    
}
